package com.xjscrm.console.queue;

import cn.hutool.core.date.DateUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.DelayQueue;

/**
 *
 */
@Slf4j
public class DelayProducer {

    public static final DelayProducer instance = new DelayProducer();

    @Getter
    private static final DelayQueue<DelayTask> delayQueue = new DelayQueue<>();

    private DelayProducer() {
    }

    public synchronized void addSendDelayTask(DelayTask delayTask) {
        if (Objects.nonNull(delayTask)) {
            if (delayQueue.contains(delayTask)) {
                log.info("添加{}, 队列中已存在相同的任务", delayTask.getName());
                delayQueue.remove(delayTask);
            }
            Long delay = delayTask.getDelay();
            log.info("添加{}, 执行时间: {}, key: {}", delayTask.getName(), DateUtil.date(delay), delayTask.getTaskId());
            delayQueue.offer(delayTask);
        }
    }

    public synchronized boolean removeSendTask(DelayTask delayTask) {
        if (Objects.nonNull(delayTask) && delayQueue.contains(delayTask)) {
            log.info("删除客服回复超时的延迟任务, key: {}", delayTask.getTaskId() + "-" + delayTask.getName());
            return delayQueue.remove(delayTask);
        }
        return false;
    }
}
